package com.simple.mqtt.server.core;

import com.simple.mqtt.server.auth.IMqttAuthHandler;
import com.simple.mqtt.server.auth.SimpleMqttAuthHandler;
import com.simple.mqtt.server.config.MqttBrokerConfig;
import com.simple.mqtt.server.serializer.IMessageSerializer;
import com.simple.mqtt.server.serializer.JsonMessageSerializer;
import com.simple.mqtt.server.session.IMqttSessionManager;
import com.simple.mqtt.server.session.InMemoryMqttSessionManager;
import com.simple.mqtt.server.store.IMqttMessageStore;
import com.simple.mqtt.server.store.InMemoryMqttMessageStore;

/**
 * MQTT代理构建器，使用建造者模式快速创建和配置
 */
public class MqttBrokerBuilder {
    // 默认监听所有网络接口
    private String host = "0.0.0.0";
    // 默认MQTT端口
    private int port = 1883;
    // 默认boss线程数
    private int bossThreads = 1;
    // 默认worker线程数 = 2倍CPU核心数
    private int workerThreads = Runtime.getRuntime().availableProcessors() * 2;
    // 默认业务线程数 = CPU核心数
    private int businessThreads = Runtime.getRuntime().availableProcessors();
    // 默认心跳超时时间2分钟（毫秒）
    private long keepAliveTimeout = 120000;
    // 默认最大消息大小10MB
    private int maxBytesInMessage = 10 * 1024 * 1024;
    // 默认最大客户端ID长度
    private int maxClientIdLength = 64;
    // 会话管理器
    private IMqttSessionManager sessionManager;
    // 消息存储
    private IMqttMessageStore messageStore;
    // 认证处理器
    private IMqttAuthHandler authHandler;
    // 消息序列化器
    private IMessageSerializer serializer;

    /**
     * 设置监听主机地址
     * @param host 主机地址，默认0.0.0.0
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder host(String host) {
        this.host = host;
        return this;
    }

    /**
     * 设置监听端口
     * @param port 端口号，默认1883
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder port(int port) {
        this.port = port;
        return this;
    }

    /**
     * 设置boss线程数
     * @param bossThreads boss线程数，默认1
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder bossThreads(int bossThreads) {
        this.bossThreads = bossThreads;
        return this;
    }

    /**
     * 设置worker线程数
     * @param workerThreads worker线程数，默认2倍CPU核心数
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder workerThreads(int workerThreads) {
        this.workerThreads = workerThreads;
        return this;
    }

    /**
     * 设置业务线程数
     * @param businessThreads 业务线程数，默认CPU核心数
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder businessThreads(int businessThreads) {
        this.businessThreads = businessThreads;
        return this;
    }

    /**
     * 设置心跳超时时间
     * @param keepAliveTimeout 心跳超时时间（毫秒），默认120000
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder keepAliveTimeout(long keepAliveTimeout) {
        this.keepAliveTimeout = keepAliveTimeout;
        return this;
    }

    /**
     * 设置最大消息大小
     * @param maxBytesInMessage 最大消息大小（字节），默认10MB
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder maxBytesInMessage(int maxBytesInMessage) {
        this.maxBytesInMessage = maxBytesInMessage;
        return this;
    }

    /**
     * 设置最大客户端ID长度
     * @param maxClientIdLength 最大客户端ID长度，默认64
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder maxClientIdLength(int maxClientIdLength) {
        this.maxClientIdLength = maxClientIdLength;
        return this;
    }

    /**
     * 设置会话管理器
     * @param sessionManager 会话管理器实例
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder sessionManager(IMqttSessionManager sessionManager) {
        this.sessionManager = sessionManager;
        return this;
    }

    /**
     * 设置消息存储
     * @param messageStore 消息存储实例
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder messageStore(IMqttMessageStore messageStore) {
        this.messageStore = messageStore;
        return this;
    }

    /**
     * 设置认证处理器
     * @param authHandler 认证处理器实例
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder authHandler(IMqttAuthHandler authHandler) {
        this.authHandler = authHandler;
        return this;
    }

    /**
     * 设置用户名/密码认证
     * @param username 用户名
     * @param password 密码
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder usernamePassword(String username, String password) {
        this.authHandler = new SimpleMqttAuthHandler(username, password);
        return this;
    }

    /**
     * 设置消息序列化器
     * @param serializer 消息序列化器实例
     * @return 当前构建器实例
     */
    public MqttBrokerBuilder serializer(IMessageSerializer serializer) {
        this.serializer = serializer;
        return this;
    }

    /**
     * 构建MqttBroker实例
     * <p>如果未指定则使用默认实现：</p>
     * <ul>
     *     <li>会话管理器：InMemoryMqttSessionManager</li>
     *     <li>消息存储：InMemoryMqttMessageStore</li>
     *     <li>认证处理器：SimpleMqttAuthHandler（无认证）</li>
     *     <li>序列化器：JsonMessageSerializer</li>
     * </ul>
     * @return MqttBroker实例
     */
    public MqttBroker build() {
        // 如果未指定则设置默认实现
        if (sessionManager == null) {
            sessionManager = new InMemoryMqttSessionManager();
        }
        if (messageStore == null) {
            messageStore = new InMemoryMqttMessageStore();
        }
        if (authHandler == null) {
            authHandler = new SimpleMqttAuthHandler();
        }
        if (serializer == null) {
            serializer = new JsonMessageSerializer();
        }

        // Create MqttBroker instance
        MqttBroker broker = new MqttBroker(
                host, port, bossThreads, workerThreads, businessThreads,
                keepAliveTimeout, maxBytesInMessage, maxClientIdLength,
                sessionManager, messageStore, authHandler, serializer
        );

        return broker;
    }

    /**
     * 构建并启动MqttBroker
     * @return 已启动的MqttBroker实例
     */
    public MqttBroker start() {
        MqttBroker broker = build();
        broker.start();
        return broker;
    }
}

